<template>
  <div>
    <!-- 首次加载过渡画面 -->
    <Transition name="fade">
      <AppLoading v-if="isLoading" :progress="loadingProgress" />
    </Transition>

    <!-- 主应用内容 -->
    <div v-show="!isLoading">
      <NuxtLoadingIndicator />
      <NuxtLayout>
        <NuxtPage />
      </NuxtLayout>
      <!-- Element Plus message and notification will be auto-injected -->
    </div>
  </div>
</template>

<script setup lang="ts">
// 加载状态管理
const isLoading = ref(true)
const loadingProgress = ref(0)

// 初始化
const siteConfig = useSiteConfig()
const userStore = useUserStore()

// SEO设置（动态）
useHead({
  titleTemplate: (title) => {
    return siteConfig.formattedTitle(title)
  }
})

// 模拟加载进度
const simulateLoading = () => {
  const interval = setInterval(() => {
    loadingProgress.value += Math.random() * 30
    if (loadingProgress.value >= 100) {
      loadingProgress.value = 100
      clearInterval(interval)
      // 延迟一点移除加载画面，让动画完成
      setTimeout(() => {
        isLoading.value = false
      }, 500)
    }
  }, 300)
}

onMounted(async () => {
  // 开始加载进度
  simulateLoading()

  // 实际的初始化操作
  try {
    if (userStore.token) {
      await userStore.getUserInfo()
      loadingProgress.value = 60
    }

    // 预加载关键资源
    await nextTick()
    loadingProgress.value = 80

    // 确保最小显示时间（避免闪烁）
    const minLoadingTime = 1500
    const startTime = Date.now()

    // 等待页面准备就绪
    await new Promise(resolve => {
      const checkReady = () => {
        if (document.readyState === 'complete') {
          resolve(true)
        } else {
          setTimeout(checkReady, 50)
        }
      }
      checkReady()
    })

    // 计算剩余的最小显示时间
    const elapsedTime = Date.now() - startTime
    const remainingTime = Math.max(0, minLoadingTime - elapsedTime)

    if (remainingTime > 0) {
      await new Promise(resolve => setTimeout(resolve, remainingTime))
    }

    // 加载完成
    loadingProgress.value = 100
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  } catch (error) {
    console.error('初始化错误:', error)
    // 出错也要移除加载画面
    loadingProgress.value = 100
    setTimeout(() => {
      isLoading.value = false
    }, 300)
  }
})
</script>

<style>
/* 淡入淡出过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
